package com.mz.service.sys;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import com.mz.base.util.ATTSystem;
import com.mz.base.util.DBUtil;
import com.mz.base.util.Page;
import com.mz.entity.SysRole;
import com.mz.service.CommonService;

public class SysRoleService {
	
	/**
	 * 查询系统角色列表
	 * @param page
	 * @param sysUsers
	 */
	public JSONArray findSysRole(){
		DBUtil db = new DBUtil();
		String sql = "select * from sys_role where status=1";
		return db.selectToJsonArray(sql);
	}
	
	/**
	 * 查询系统角色列表
	 * @param page
	 * @param sysRole
	 */
	public void findSysRole(Page page, SysRole sysRole){
		DBUtil db = new DBUtil();
		String sql = "select * from sys_role where status<>"+ATTSystem.MARK_DELETE;
		if(sysRole!=null){
			String where = CommonService.objectToWhere(sysRole);
			if(!StringUtils.isEmpty(where)){
				sql += " and " + where;
			}
		}
		db.search(page, sql);
	}
	/**
	 * 保存系统角色信息
	 * @param sysRole
	 * @return
	 */
	public int saveSysRole(SysRole sysRole){
		DBUtil db = new DBUtil();
		int rows = 0;
		if(sysRole.getRoleId()!=null){
			String sql = "update sys_role set roleName='" + sysRole.getRoleName()+"', " +
											  "status=" + sysRole.getStatus() + ", " +
											  "updateTime=now(), " +
											  "updateUser=" + sysRole.getUpdateUser() + 
						 " where roleId="+sysRole.getRoleId();
			rows = db.update(sql);
		}else{
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String[] fields = new String[]{"roleName", "status", "createTime", "createUser", "updateTime", "updateUser"};
			Object[] values = new Object[]{sysRole.getRoleName(), sysRole.getStatus(), format.format(sysRole.getCreateTime()), 
					sysRole.getCreateUser(), format.format(sysRole.getUpdateTime()), sysRole.getUpdateUser()};
			rows = db.insert("sys_role", fields, values);
		}
		return rows;
	}
	/**
	 * 获取系统角色信息
	 * @param roleId
	 * @return
	 */
	public JSONObject getSysRoleById(Long roleId){
		DBUtil db = new DBUtil();
		String sql = "select * from sys_role where roleId="+roleId;
		return db.selectToJson(sql);
	}
	/**
	 * 删除系统角色账号
	 * @param roleId
	 * @param sessionUserId
	 * @return
	 */
	public int deleteSysRole(Long roleId, Long sessionUserId){
		DBUtil db = new DBUtil();
		String sql = "update sys_role set status=-1, updateTime=now(), updateUser="+sessionUserId+" where roleId="+roleId;
		return db.update(sql);
	}
	/**
	 * 获取用户的权限菜单关联信息
	 * @param roleId
	 * @return
	 */
	public JSONObject queryRoleJoinMenu(Long roleId){
		DBUtil db = new DBUtil();
		String sql = "select menuId from sys_role_menu where roleId="+roleId;
		JSONArray array = db.selectToJsonArray(sql);
		
		JSONObject json = new JSONObject();
		
		if(array!=null && array.length()>0){
			for(int i=0,len=array.length(); i<len; i++){
				json.put("I_"+array.getJSONObject(i).getInt("menuId"), true);
			}
		}
		return json;
	}
	/**
	 * 更新用户权限菜单
	 * @param roleMenuList
	 * @return
	 */
	public Boolean saveRoleMenu(Long[] menuIdArray, Long roleId){
		DBUtil db = new DBUtil();
		String sql = "delete from sys_role_menu where roleId="+roleId;
		db.delete(sql);
		
		if(menuIdArray!=null && menuIdArray.length>0){
			for(Long menuId : menuIdArray){
				db.insert("INSERT INTO sys_role_menu(roleId, menuId) VALUES("+roleId+", "+menuId+")");
			}
		}
		
		ATTSystem.MAP_ROLE_MENU.remove("ROLE_"+roleId);
		
		this.findSysMenuJoinRole();
		
		return true;
	}
	/**
	 * 获取用户的权限菜单
	 * @param roleId
	 * @return
	 */
	public JSONArray getRoleMenu(Long roleId){
		JSONArray array = new JSONArray();
		array = ATTSystem.MAP_ROLE_MENU.get("ROLE_"+roleId);
		
		if(array==null || array.length()==0){
			DBUtil db = new DBUtil();
			String sql = "select b.menuCode, b.menuName, b.url, b.parameter, b.target from sys_role_menu a, sys_menu b " +
						 "where a.menuId=b.menuId and a.roleId="+roleId+" and b.`status`=1 and b.menuCode like '___' " +
						 "order by b.orderNum";
			JSONArray jsonMenu1 = db.selectToJsonArray(sql);
			
			JSONArray retJson = new JSONArray();
			for(int i=0,len=jsonMenu1.length(); i<len; i++){
				JSONObject json = jsonMenu1.getJSONObject(i);
				sql = "select b.menuCode, b.menuName, b.url, b.parameter, b.target from sys_role_menu a, sys_menu b " +
					  "where a.menuId=b.menuId and a.roleId="+roleId+" and b.`status`=1 and " +
							"b.menuCode like '"+json.getString("menuCode")+"___' order by b.orderNum";
				JSONArray jsonMenu2 = db.selectToJsonArray(sql);
				
				json.put("list", jsonMenu2);
				retJson.put(i, json);
			}
			array = retJson;
			ATTSystem.MAP_ROLE_MENU.put("ROLE_"+roleId, array);
		}
		
		return array;
	}
	/**
	 * 获取菜单所属权限
	 */
	public void findSysMenuJoinRole(){
		Map<String, List<Long>> map = new HashMap<String, List<Long>>();
		DBUtil db = new DBUtil();
		String sql = "select m.menuName, m.url, rm.roleId from sys_menu m left join sys_role_menu rm on m.menuId=rm.menuId " +
					 "where m.url is not null and m.url!='' and m.status=1";
		JSONArray array = db.selectToJsonArray(sql);
		
		if(array!=null){
			for(int i=0,len=array.length(); i<len; i++){
				JSONObject json = array.getJSONObject(i);
				String uri = json.getString("url");
				List<Long> list = new ArrayList<Long>();
				if(map.get(uri) != null){
					list = map.get(uri);
				}
				Long roleId = json.getLong("roleId");
				
				if(roleId != null){
					list.add(roleId);
				}
				map.put(uri, list);
			}
		}
		
		ATTSystem.MAP_MENU_URI_ROLE = map;
	}
}